# Maintainer: George Rawlinson <grawlinson@archlinux.org>

pkgname=buf
pkgver=1.27.2
pkgrel=1
pkgdesc='A tool for working with Protocol Buffers'
arch=('loong64' 'x86_64')
url='https://buf.build'
license=('Apache')
depends=('glibc')
makedepends=('git' 'go')
options=('!lto')
_commit='a987d2dfc1ad7cf9d07dfd824ae0dea15d126c59'
source=("$pkgname::git+https://github.com/bufbuild/buf#commit=$_commit")
b2sums=('SKIP')

pkgver() {
  cd "$pkgname"

  git describe --tags | sed 's/^v//'
}

prepare() {
  cd "$pkgname"

  # create directory for build output
  mkdir build

  # download dependencies
  export GOPATH="${srcdir}"
  go mod download
}

build() {
  cd "$pkgname"

  # set Go flags
  export CGO_CPPFLAGS="${CPPFLAGS}"
  export CGO_CFLAGS="${CFLAGS}"
  export CGO_CXXFLAGS="${CXXFLAGS}"
  export GOPATH="${srcdir}"

  go build -v \
    -buildmode=pie \
    -mod=readonly \
    -modcacherw \
    -ldflags "-compressdwarf=false \
    -linkmode external \
    -extldflags ${LDFLAGS}" \
    -o build \
    ./cmd/...

  # generate shell completions
  for shell in bash fish zsh; do
    ./build/buf completion "$shell" > "build/completion.$shell"
  done

  # generate manpages
  mkdir -p build/manpages
  ./build/buf manpages build/manpages

  # ensure manpages are reproducible
  local _commit_date=$(git show --no-patch --format=%cd --date=format:%Y-%m-%d)
  sed \
  -e "s/^\(\.TH.* \"\)\w\{3\} [0-9]\{4\}/\1${_commit_date}/" \
  -e "s/.*\( Auto generated by spf13\/cobra\)$/${_commit_date}\1/" \
  -i build/manpages/*
}

package() {
  cd "$pkgname"

  # binaries
  install -vDm755 -t "$pkgdir/usr/bin" build/{buf,protoc-gen-buf-lint,protoc-gen-buf-breaking}

  # shell completions
  install -vDm644 build/completion.bash "$pkgdir/usr/share/bash-completion/completions/buf"
  install -vDm644 build/completion.fish "$pkgdir/usr/share/fish/vendor_completions.d/buf.fish"
  install -vDm644 build/completion.zsh "$pkgdir/usr/share/zsh/site-functions/_buf"

  # man pages
  install -vDm644 build/manpages/* -t "$pkgdir/usr/share/man/man1"
}
